package com.study.servlet.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @Name: CookieServletDemo01
* @Description: 浏览器Cookie操作
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-3-1 下午8:48:48 
* @Version: V1.0
 */
public class CookieServletDemo02 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8") ;
		PrintWriter out = response.getWriter() ;
		out.print("当前时间是：") ;
		//得到浏览器中所有的Cookie
		Cookie[] cookies = request.getCookies() ;
		//查找自己想要的Cookie
		if(cookies != null && cookies.length > 0) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = cookies[i] ;
				if("myCookieTime".equals(cookie.getName())) {
					String value = cookie.getValue() ;
					Date date = new Date(Long.valueOf(value)) ;
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss") ;
					String result = sdf.format(date) ;
					//显示
					out.write(result) ;
					break ;
				}
			}
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}
